<template>
  <div class="app-container">
    <!-- 筛选栏 -->
    <div v-show="showSearch">
      <!-- 搜索表单 -->
      <el-form :inline="true" ref="queryForm">
        <el-form-item label="视频标题" size="small">
          <el-input
            v-model="queryParams.title"
            placeholder="请输入视频标题"
            clearable
          ></el-input>
        </el-form-item>
        <!-- <el-form-item label="课程名称" size="small">
          <el-select
            v-model="queryParams.courseId"
            placeholder="默认全部"
            clearable
          >
            <el-option
              v-for="item in courseList"
              :key="item.id"
              :label="item.title"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </el-form-item> -->
        <el-form-item label="发布状态" size="small">
          <el-select
            v-model="queryParams.status"
            placeholder="默认全部"
            clearable=""
          >
            <el-option
              v-for="item in statusOption"
              :key="item.id"
              :label="item.label"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <!-- 视频类型：独立视频和课程视频 -->
        <!-- <el-form-item label="视频类型" size="small">
          <el-select
            v-model="queryParams.type"
            placeholder="默认全部"
            clearable=""
          >
            <el-option
              v-for="item in videoType"
              :key="item.id"
              :label="item.label"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </el-form-item> -->
        <el-form-item size="small">
          <el-button type="primary" icon="el-icon-search" @click="getList"
            >搜索</el-button
          >
          <el-button icon="el-icon-refresh" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
    </div>
    <!-- 表格上方按钮 -->
    <div>
      <div style="float: left; margin-bottom: 10px">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="small"
          @click="preAdd"
          >新增独立视频</el-button
        >
      </div>
      <right-toolbar
        :showSearch.sync="showSearch"
        @queryTable="getList"
        style="float: right"
      ></right-toolbar>
    </div>
    <!-- 信息列表 -->
    <div style="float: left; width: 100%">
      <el-table
        border
        v-loading="listLoading"
        :header-cell-style="{ background: '#FAFAFA' }"
        :data="videoList"
        style="width: 100%"
        height="75vh"
      >
        <el-table-column prop="id" label="视频id"> </el-table-column>
        <el-table-column prop="title" label="标题"> </el-table-column>

        <el-table-column label="封面">
          <template slot-scope="scope">
            <img
              v-if="scope.row.cover"
              :src="scope.row.cover"
              width="80"
              height="50"
            />
            <!-- 图片为空时，显示默认图片 -->
            <img
              v-if="!scope.row.cover"
              src="@/assets/default.jpg"
              width="80"
              height="50"
            />
          </template>
        </el-table-column>
        <!-- <el-table-column prop="type" label="视频类型"> </el-table-column> -->
        <el-table-column prop="size" label="大小（MB）"> </el-table-column>
        <el-table-column
          label="创建时间"
          prop="gmtCreate"
          width="180px"
          :show-overflow-tooltip="true"
          sortable
        >
        </el-table-column>
        <el-table-column
          label="最后修改时间"
          prop="gmtModified"
          :show-overflow-tooltip="true"
          width="180px"
          sortable
        >
        </el-table-column>
        <el-table-column label="是否发布" align="center" key="status">
          <template slot-scope="scope">
            <el-switch
              v-model="scope.row.status"
              active-text="是"
              inactive-text="否"
              active-value="1"
              inactive-value="0"
              @change="handleStatusChange(scope.row)"
            ></el-switch>
          </template>
        </el-table-column>
        <el-table-column fixed="right" label="操作" width="180" align="center">
          <template slot-scope="scope">
            <el-button
              type="text"
              size="medium"
              @click="modifyVideo(scope.row)"
            >
              编辑
            </el-button>
            <el-button
              type="text"
              size="medium"
              @click="deleteVideo(scope.row)"
            >
              删除
            </el-button>
            <el-button
              type="text"
              size="medium"
              @click="previewVideo(scope.row)"
            >
              播放
            </el-button>
            <el-button
              type="text"
              size="medium"
              @click="studyRecord(scope.row)"
            >
              学习记录
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <div style="width: 100%; text-align: center; margin-top: 10px">
        <el-pagination
          @size-change="sizeChange"
          @current-change="goto"
          :current-page="page.current"
          :page-sizes="[5, 10, 15, 20]"
          :page-size="page.size"
          layout="total, sizes, prev, pager, next, jumper"
          :total="page.total"
          background
          style="float: right"
        >
        </el-pagination>
      </div>
    </div>
    <!-- 上传对话框 -->
    <el-dialog
      title="新增独立视频"
      :visible.sync="uploadDialog"
      width="30%"
      :before-close="handleClose"
    >
      <el-form
        ref="uploadForm"
        :rules="rules"
        :model="uploadForm"
        label-width="80px"
      >
        <el-row>
          <el-form-item label="视频标题" prop="title">
            <el-input
              v-model="uploadForm.title"
              placeholder="请输入视频标题"
              maxlength="30"
            />
          </el-form-item>
        </el-row>
        <!-- <el-row> -->
        <!-- <el-form-item label="对应课程" prop="courseId">
            <el-select v-model="uploadForm.courseId" placeholder="可不选择">
              <el-option
                v-for="item in courseList"
                :key="item.id"
                :label="item.title"
                :value="item.id"
              >
              </el-option>
            </el-select>
          </el-form-item> -->
        <!-- </el-row> -->
        <el-row>
          <el-form-item label="视频选取" prop="videoSourceId">
            <VideoUpload @upload-success="afterUploadAddVideo"></VideoUpload>
            <!-- <el-upload
              :action="upload.videoUrl"
              :on-remove="handleVodRemoveVideo"
              ref="uploadVideo"
              accept=".mp4"
              :limit="1"
              :on-success="afterUploadVideo"
              :auto-upload="true"
              style="display: inline-block"
            >
              <el-button type="primary" size="small">上传视频</el-button>
              <div slot="tip" class="el-upload__tip">只能上传mp4文件</div>
            </el-upload> -->
          </el-form-item>
        </el-row>
        <el-row>
          <el-form-item label="视频封面" prop="cover">
            <el-upload
              ref="uploadImg"
              :on-remove="handleVodRemoveImg"
              :action="upload.imgUrl"
              :limit="1"
              :auto-upload="true"
              :on-success="afterUploadImg"
              accept=".jpg, .jpeg, .png, .JPG, .JPEG"
              list-type="picture"
            >
              <el-button size="small" type="primary">选取封面</el-button>
              <div slot="tip" class="el-upload__tip">
                只能上传jpg/jpeg/png文件
              </div>
            </el-upload>
          </el-form-item>
        </el-row>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="uploadDialog = false">取 消</el-button>
        <el-button
          type="primary"
          :disabled="saveVideoBtnDisabled"
          @click="submitUpload"
          >确 定</el-button
        >
      </span>
    </el-dialog>
    <!-- 修改对话框 -->
    <el-dialog
      title="视频信息修改"
      :visible.sync="modifyDialog"
      width="30%"
      :before-close="handleClose"
    >
      <el-form
        ref="modifyForm"
        :rules="rules"
        :model="modifyForm"
        label-width="80px"
      >
        <el-row>
          <el-form-item label="视频标题" prop="title">
            <el-input
              v-model="modifyForm.title"
              placeholder="请输入视频标题"
              maxlength="30"
            />
          </el-form-item>
        </el-row>
        <el-row>
          <!-- <el-form-item label="对应课程" prop="courseId">
            <el-select v-model="modifyForm.courseId">
              <el-option
                v-for="item in courseList"
                :key="item.id"
                :label="item.title"
                :value="item.id"
              >
              </el-option>
            </el-select>
          </el-form-item> -->
          <el-form-item label="视频封面" prop="cover">
            <img :src="modifyForm.cover" width="100" />
            <el-upload
              ref="uploadImg"
              :action="upload.imgUrl"
              :limit="1"
              :auto-upload="true"
              :on-success="afterUploadImg"
              accept=".jpg, .jpeg, .png, .JPG, .JPEG"
            >
              <el-button size="small" type="success">选取封面</el-button>
              <div slot="tip" class="el-upload__tip">
                只能上传jpg/jpeg/png文件
              </div>
            </el-upload>
          </el-form-item>
          <el-form-item label="视频修改" prop="videoSourceId">
            <VideoUpload @upload-success="afterUploadModifyVideo"></VideoUpload>
            <!-- <el-upload
              :action="upload.videoUrl"
              ref="uploadVideo"
              accept=".mp4"
              :limit="1"
              :on-success="afterUploadVideo"
              :auto-upload="true"
              style="display: inline-block"
            >
              <el-button type="primary" size="small">上传视频</el-button>
              <div slot="tip" class="el-upload__tip">只能上传mp4文件</div>
            </el-upload> -->
          </el-form-item>
        </el-row>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="modifyDialog = false">取 消</el-button>
        <el-button type="primary" @click="updateVideo()">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 预览对话框 -->
    <el-dialog title="预览" width="80%" :visible.sync="dialogPlayVisible">
      <play :videosource="videosource" v-if="dialogPlayVisible"></play>
    </el-dialog>
  </div>
</template>

<script>
import {
  queryList,
  addVideoInfo,
  updateStatus,
  removeVideo,
  modifyVideoInfo,
} from "@/api/video";

import play from "./play";
import { getAllCourse } from "@/api/edu/course";
import { mapGetters } from "vuex";
import VideoUpload from "@/components/VideoUpload";

// 引入分块上传文件方法
// import { upload, uploadByPieces } from "@/utils/upload.js";

export default {
  name: "document",
  computed: {
    ...mapGetters(["companyId"]),
  },
  created: function () {
    this.getList();
    //查询所有课程列表
    getAllCourse(this.companyId).then((res) => {
      const data = res.data;
      this.courseList = data.list;
    });
  },
  components: {
    play,
    VideoUpload,
  },
  data: function () {
    return {
      // data是上传视频时附带的额外参数
      data: {},
      //课程列表
      courseList: [],
      //课程列表
      courseList: [],
      //状态选项
      statusOption: [
        { label: "上架", id: "1" },
        { label: "下架", id: "0" },
      ],
      //视频类型
      videoType: [
        { label: "独立视频", id: "独立视频" },
        { label: "课程视频", id: "课程视频" },
      ],
      //表格加载遮罩
      listLoading: "false",
      //搜索表单
      queryParams: {
        title: "",
        courseId: "",
        status: "",
        type: "",
      },
      //分页设置
      page: {
        current: 1,
        total: 0,
        size: 5,
      },
      //视频列表
      videoList: [],
      //上传对话框
      uploadDialog: false,
      //是否上传视频成功
      isUploadVideo: false,
      //是否上传封面成功
      isUploadCover: false,
      //预览对话框
      dialogPlayVisible: false,
      //视频资源信息
      videosource: {},
      //上传教材表单
      uploadForm: {},
      //上传设置
      upload: {
        //封面上传的地址
        imgUrl: process.env.BASE_API + "/oss/file/photo",
        // 视频上传的地址
        videoUrl: process.env.BASE_API + "/vod/uploadVideo",
      },
      //修改的对话框
      modifyDialog: false,
      //修改的表单
      modifyForm: {},
      //是否显示搜索表单
      showSearch: true,
      //表单验证
      rules: {
        title: [{ required: true, message: "请输入标题", trigger: "blur" }],
        cover: [{ required: true, message: "请上传封面", trigger: "blur" }],
        videoSourceId: [
          { required: true, message: "请上传视频", trigger: "blur" },
        ],
      },
      //是否显示保存按钮
      saveVideoBtnDisabled: true,
    };
  },
  methods: {
    //获取视频列表
    getList: function () {
      let params = this.queryParams;
      params.limit = this.page.size;
      params.current = this.page.current;
      let that = this;
      this.listLoading = true;
      //表格数据列表
      queryList(params, this.page.current, this.page.size, this.companyId).then(
        (res) => {
          const data = res.data;
          that.page.total = data.total;
          that.videoList = data.rows;
          this.listLoading = false;
        }
      );
    },
    handleVodRemoveImg() {
      this.uploadForm.cover = "";
    },
    handleVodRemoveVideo() {
      this.uploadForm.videoSourceId = "";
    },
    //查看学习记录
    studyRecord(row) {
      this.$router.push({
        name: "VideoStudyRecord",
        query: {
          id: row.id,
          videoName: row.title,
          type: "0",
        },
      });
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.queryParams = {
        title: "",
        courseId: "",
        status: "",
        type: "",
      };
      this.getList();
    },
    //点击新增预处理
    preAdd() {
      this.uploadForm = {
        courseId: "", //所属课程id
        cover: "", //封面
        title: "", //标题
        videoSourceId: "", //上传后视频id
        type: "", //视频类型
        size: "", //视频大小
      };
      //上传前确认按钮不可用
      this.saveVideoBtnDisabled = true;
      //重置表单
      if (this.$refs["uploadForm"] !== undefined) {
        this.$refs["uploadForm"].resetFields();
      }
      if (this.$refs["uploadImg"] !== undefined) {
        this.$refs["uploadImg"].clearFiles();
      }
      this.uploadDialog = true;
    },

    //自定义视频上传组件，成功上传新增视频后
    afterUploadAddVideo(response) {
      this.isUploadVideo = true;
      //上传
      this.uploadForm.type = "独立视频";
      this.uploadForm.videoSourceId = response.videoId;
      this.uploadForm.size = response.fileSize;
      //上传视频成功后确认按钮生效
      if (response.success) {
        this.saveVideoBtnDisabled = false;
      }
    },
    //自定义视频上传组件，成功上传修改视频后
    afterUploadModifyVideo(response) {
      this.isUploadVideo = true;
      //修改
      this.modifyForm.type = "独立视频";
      this.modifyForm.videoSourceId = response.videoId;
      this.modifyForm.size = response.fileSize;
    },
    //成功上传封面后
    afterUploadImg(response) {
      this.isUploadCover = true;
      this.uploadForm.cover = response.data.url;
      this.modifyForm.cover = response.data.url;
    },
    //新增视频信息
    submitUpload() {
      let that = this;
      if (this.uploadForm.cover == "" || this.uploadForm.videoSourceId == "") {
        this.$message({
          message: "请选择视频封面",
          type: "warning",
        });
      } else {
        if (that.$refs["uploadForm"] !== undefined) {
          that.$refs["uploadForm"].validate((valid) => {
            if (!that.isUploadVideo || !that.isUploadCover) {
              this.$message({
                message: "正在上传中，请先稍等",
                type: "warning",
              });
              return false;
            } else if (valid) {
              that.uploadForm.companyId = this.companyId;
              addVideoInfo(that.uploadForm, this.companyId).then((res) => {
                if (res.success == true) {
                  this.$message({
                    message: "提交成功",
                    type: "success",
                  });
                  that.getList();
                  that.uploadDialog = false;
                } else {
                  this.$message({
                    message: "提交失败",
                    type: "error",
                  });
                }
                that.isUploadVideo = false;
                that.isUploadCover = false;
              });
            } else {
              return false;
            }
          });
        }
      }
    },
    //关闭对话框
    handleClose(done) {
      this.$confirm("确认关闭？")
        .then((_) => {
          done();
        })
        .catch((_) => {});
    },
    //课件发布状态修改
    handleStatusChange(row) {
      // console.log(row);
      updateStatus(row.id, row.status).then((res) => {
        if (res.success == true) {
          this.$message({
            message: "修改成功",
            type: "success",
          });
        } else {
          this.$message({
            message: "修改失败",
            type: "error",
          });
        }
        this.getList();
      });
    },
    //删除单个文件
    deleteVideo: function (row) {
      var self = this;
      this.$confirm("此操作将删除该视频, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          var idArray = []; //删除列表
          idArray.push(row.id);
          self.deleteAjax(idArray);
        })
        .catch(() => {});
    },
    //删除Ajax请求
    deleteAjax: function (idArray) {
      var that = this;
      removeVideo(idArray[0]).then((res) => {
        if (res.success == true) {
          this.$message({
            message: "删除成功",
            type: "success",
          });
          that.getList();
        } else {
          this.$message({
            message: "删除失败",
            type: "error",
          });
        }
      });
    },
    //点击修改图片后
    afterModifyImg(response) {
      this.modifyForm.cover = response.data.url;
    },
    //修改预处理
    modifyVideo(row) {
      this.modifyForm = row;
      if (this.$refs["modifyImg"] !== undefined) {
        this.$refs["modifyImg"].clearFiles();
      }
      if (this.$refs["modifyVideo"] !== undefined) {
        this.$refs["modifyImg"].clearFiles();
      }
      this.modifyDialog = true;
    },
    //提交修改
    updateVideo() {
      let that = this;
      if (this.modifyForm.title == "") {
        this.$message({
          message: "标题不能为空",
          type: "warning",
        });
      } else {
        modifyVideoInfo(that.modifyForm).then((res) => {
          if (res.success == true) {
            this.$message({
              message: "成功",
              type: "success",
            });
            that.getList();
            that.modifyDialog = false;
          } else {
            this.$message({
              message: "失败",
              type: "error",
            });
          }
          that.isUploadVideo = false;
          that.isUploadCover = false;
        });
      }
    },
    //预览视频
    previewVideo: function (row) {
      this.videosource = row;
      this.dialogPlayVisible = true;

      //跳转新页面播放
      // let videoUrl = "";
      // let videoSourceId = "";
      // getVideoSourceId(this.videosource.id).then((res) => {
      //   videoSourceId = res.data.videoSourceId;
      //   getVideoUrl(videoSourceId).then((res) => {
      //     videoUrl = res.data.playUrl;
      //     window.open(videoUrl);
      //   });
      // });
    },
    //跳转页面
    goto: function (current) {
      this.page.current = current;
      this.getList();
    },
    //页码改变
    sizeChange: function (size) {
      this.page.size = size;
      this.getList();
    },
  },
};
</script>

<style scoped>
</style>
